// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  console.log(event)
  console.log("123")
   let u =  db.collection('user').where({ _openid:wxContext.OPENID }).get();
     if((await u).data.length == 0 ){
       //新人
         let  i =await db.collection('user').add({
        data: {_openid:wxContext.OPENID,
          nickName:event.nickName,
          gender:event.gender,
          language:event.language,
          city:event.city,
          province:event.province,
          country:event.country,
          avatarUrl:event.avatarUrl,
          dateAdd:event.dateAdd,
          isnewUser:true,
          status:event.status,
               },
        success(res) { //成功打印消息
          console.log('3', res)
        },
        fail(res) { //存入数据库失败
          console.log('订单存入数据库操作失败');
          //云函数更新
        }
      });
      console.log(i)
      return{user:await db.collection('user').where({ _openid:wxContext.OPENID }).get(),
        openid:wxContext.OPENID,
       

    }
     }else{
       console.log(event)
      let  i =await db.collection('user').doc((await u).data[0]._id).update({
        data: {_openid:wxContext.OPENID,
          nickName:event.nickName,
          gender:event.gender,
          language:event.language,
          city:event.city,
          province:event.province,
          country:event.country,
          avatarUrl:event.avatarUrl,
          dateAdd:event.dateAdd,
          
               },
        success(res) { //成功打印消息
          console.log('3', res)
         
       
        },
        fail(res) { //存入数据库失败
          console.log('订单存入数据库操作失败');
          //云函数更新
        }
      });
      
        return {user:await db.collection('user').where({ _openid:wxContext.OPENID }).get(),
        openid:wxContext.OPENID,
        isnewUser:true
        }
       
    
     }
    
}